import {Config} from '../utils/config.js';
import {Token} from "./token.js";

class Base{
   constructor(){
      this.baseRequestUrl = Config.baseRequestUrl;
   }
   //noRefetch是为了避免未授权，重试机制
   request(params, noRefetch){
      var that = this;
      if(!params.type){
         params.type = 'GET';
      }
      wx.request({
         url: this.baseRequestUrl + params.url,
         method: params.type,
         data: params.data,
         header: {'content-type':'application/json','token':wx.getStorageSync('token')},
         success: function(res) {
            let statusCode = res.statusCode.toString();
            let firstCode = statusCode.charAt(0);
            if(firstCode == '2'){
               params.scallback && params.scallback(res.data);
            }else {
               if (firstCode == '4'){
                  if(!noRefetch){
                     that._refetch(params);
                  }
               }
               //第一次调用失败后，当第二次再次调用的时候就调取ecallback
               if (noRefetch){
                  params.ecallback && params.ecallback(false);
               }
            }
         },
         fail: function(res){
             //例如无法联网时调用
         }
      })
   }
   //用于状态不为2的时候向服务器发送请求,直到请求状态码为2
   _refetch(params){
      var token = new Token;
      token.getTokenFromServer((token) => {
         this.request(params, true);
      });
   }
}
export {Base}